package com.spark.trouble.handle

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.widget.LinearLayoutManager
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.common.Const
import com.spark.common.ext.cancel
import com.spark.common.ext.report
import com.spark.common.ext.wrapIO
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.trouble.R
import com.spark.trouble.model.ChkStdDirFilterModel
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.win_directory.*
import org.json.JSONArray
import org.json.JSONObject

/**
 * 考核标准-目录过滤
 */
class DirFilterDF : DialogFragment() {
    private lateinit var chkStdDirAdapter: ChkStdDirAdapter
    private var dispose: Disposable? = null


    companion object {
        private var onFilterSelectListener: OnFilterSelectListener? = null
        fun newInstance(listener: OnFilterSelectListener?): DirFilterDF {
            val dirFilterDF = DirFilterDF()
            onFilterSelectListener = listener
            return dirFilterDF
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val window = dialog.window
        val rootView = inflater.inflate(R.layout.win_directory, window.findViewById(android.R.id.content) as ViewGroup, false)
        window.apply {
            setGravity(Gravity.TOP)
            setLayout(-1, -2)
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        }
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        chkStdDirAdapter = ChkStdDirAdapter(R.layout.item_direc_one)
        recy_dirs.apply {
            adapter = chkStdDirAdapter
            layoutManager = LinearLayoutManager(context)
        }
        fetchDirs()
        tv_reset.setOnClickListener { chkStdDirAdapter.reset() }
        btn_affirm.setOnClickListener {
            onFilterSelectListener?.onFilterChecked(chkStdDirAdapter.summary())
            dismiss()
        }
        iv_back.setOnClickListener { dismiss() }
        tv_title.text = "选择考核标准"
    }

    override fun onDismiss(dialog: DialogInterface?) {
        super.onDismiss(dialog)
        dispose?.cancel()
    }

    @SuppressLint("CheckResult")
    fun fetchDirs() {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_chk_std_dir}", "{}".toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ChkStdDirFilterModel::class.java)?.apply {
                                if (code == "200") {
                                    val files = mutableListOf<ChkStdDirFilterModel.ResultMap>()
                                    val ja = JSONArray(data.treejson)
                                    for (i in 0 until ja.length()) {
                                        val jo = JSONObject(ja[i].toString())
                                        val file = ChkStdDirFilterModel.ResultMap()
                                        if (jo.has("id"))
                                            file.id = jo.getInt("id")
                                        if (jo.has("name"))
                                            file.name = jo.getString("name")
                                        files.add(file)
                                    }
                                    chkStdDirAdapter.addData(files)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }
}

class ChkStdDirAdapter(layoutRes: Int) : BaseQuickAdapter<ChkStdDirFilterModel.ResultMap, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: ChkStdDirFilterModel.ResultMap?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_dir_one, item.name)
            val cbOne = getView<CheckBox>(R.id.cb_one)
            cbOne.setOnCheckedChangeListener { buttonView, isChecked ->
                item.isChecked = isChecked
            }
            setOnItemClickListener { adapter, view, position ->
                cbOne.isChecked = item.isChecked
            }
        }
    }

    fun reset() {
        data.forEach {
            it.isChecked = false
        }
        notifyDataSetChanged()
    }

    fun summary(): String {
        var result = ""
        data.forEach {
            if (it.isChecked)
                result = "${it.id},$result"
        }
        return result
    }

}